import {
  Breadcrumb,
  Button,
  Card,
  DatePicker,
  Form,
  message,
  Modal,
  Radio,
  Space,
  Table,
  Tag,
} from 'antd';
import { delArticleByIdAPI, getArticleListAPI } from 'api/article';

import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import errorSrc from 'asstes/error.png';
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import Channel from 'components/Channel';
import { useHistory } from 'react-router-dom';

const { RangePicker } = DatePicker;

const articleStatus = [
  { id: -1, name: '全部', color: 'magenta' },
  { id: 0, name: '草稿', color: 'orange' },
  { id: 1, name: '待审核', color: 'red' },
  { id: 2, name: '审核通过', color: 'green' },
  { id: 3, name: '审核失败', color: 'cyan' },
];

export default function ArticleList() {
  const [articleData, setArticleData] = useState({});

  // 1. 创建history
  const history = useHistory();
  const formDataRef = useRef();

  const handleSubmit = (values) => {
    let formData = { ...values };

    if (formData.status === -1) {
      delete formData.status;
    }

    if (formData.date) {
      const begin_pubdate = formData.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const end_pubdate = formData.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');

      formData.begin_pubdate = begin_pubdate;
      formData.end_pubdate = end_pubdate;
    }

    delete formData.date;

    formDataRef.current = formData;

    loadArticles(formData);
  };

  const loadArticles = async (params) => {
    const res = await getArticleListAPI(params);
    setArticleData(res.data);
  };

  const handlePageChange = (page, pageSize) => {
    loadArticles({ page, per_page: pageSize, ...formDataRef.current });
  };

  const handleDelById = (id) => {
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除这篇文章?',
      okText: '确认',
      cancelText: '取消',

      onOk: async () => {
        await delArticleByIdAPI(id);
        loadArticles({
          ...formDataRef.current,
          page: articleData.page,
          per_page: articleData.per_page,
        });
        message.success('删除成功', 1);
      },
    });
  };

  useEffect(() => {
    loadArticles({});
  }, []);

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (value) => {
        if (!value.images.length) {
          return <img width={150} src={errorSrc} alt="" />;
        }
        return <img width={150} src={value.images[0]} alt="" />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',

      render: (value) => {
        const info = articleStatus.find((item) => item.id === value);
        return <Tag color={info.color}>{info.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      render: (value, record, index) => {
        // record代表的是一行数据，将来可以根据record.id去删除一条数据
        return (
          <Space>
            <Button
              // 3. 点击跳转到编辑路由，记得传参id
              onClick={() => history.push('/edit/' + record.id)}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
            ></Button>
            <Button
              onClick={() => handleDelById(record.id)}
              danger
              type="primary"
              shape="circle"
              icon={<DeleteOutlined />}
            ></Button>
          </Space>
        );
      },
    },
  ];

  return (
    <div>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
      >
        <Form
          onFinish={handleSubmit}
          initialValues={{ status: -1, channel_id: 0 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>
          {/* 1. ArticleList中保留Channel组件，删掉未封装的频道列表
     2. 验证ArticleList的功能仍旧正常  */}
          <Form.Item label="频道" name="channel_id">
            <Channel />
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="snbmit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        根据筛选条件共查询到 {articleData.total_count} 条结果：
        <Table
          pagination={{
            current: articleData.page,

            total: articleData.total_count,
            position: ['bottomCenter'],
            pageSize: articleData.per_page,
            onChange: handlePageChange,
          }}
          columns={columns}
          dataSource={articleData.results}
          rowKey="id"
        ></Table>
      </Card>
    </div>
  );
}
